package ru.amse.jsynchro.fileSystem;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import ru.amse.jsynchro.kernel.DirectoryTree;
import ru.amse.jsynchro.kernel.IDirectoryTree;
import ru.amse.jsynchro.net.stream.LimitedInputStream;
import ru.amse.jsynchro.net.stream.LimitedOutputStream;

@SuppressWarnings("serial")
public class LocalFileSystem implements FileSystem {
    public InputStream openInputStream(String path, long length) throws FileNotFoundException{
        return new LimitedInputStream((InputStream) new FileInputStream(path), length);
    }
    
    public OutputStream openOutputStream(String path, long length) throws FileNotFoundException {
        return new LimitedOutputStream((OutputStream) new FileOutputStream(path), length);
    }
    
    public void closeInputStream(InputStream is) throws IOException {
        is.close();
    }
    
	public IDirectoryTree getDirectoryTree(String root) {
		return new DirectoryTree(new File(root), this);
	}
    
    public void makeDir(File dir) throws IOException {
        if (!dir.mkdir()) {
            throw new IOException("can't create dir: " + dir.getPath());
        }
    }

    public File[] listFiles(File dir) throws IOException {
        return dir.listFiles();
    }
    
    public boolean deleteFile(File f) throws IOException {
        return f.delete();
    }
    
    public void closeOutputStream(OutputStream os) throws IOException {
        os.close();
    }

    public long getFileLength(String path) throws IOException {
        File f = new File(path);
//        if (!f.exists()) {
//            throw new IOException();
//        }
        return f.length();
    }

    @Override
    public boolean isDirectory(File file) throws IOException {
        return file.isDirectory();
    }

    public void attrExecute(File file) throws IOException {
        if (file.canExecute()) {
            file.setExecutable(false);
        } else {
            file.setExecutable(true);
        }
    }

    public void attrHidden(File file) throws IOException {
//        if (file.canExecute()) {
//            file.setExecutable(false);
//        } else {
//            file.setExecutable(true);
//        }
    }

    public void attrRead(File file) throws IOException {
        if (file.canRead()) {
            file.setReadable(false);
        } else {
            file.setReadable(true);
        }
        
    }

    public void attrWrite(File file) throws IOException {
        if (file.canWrite()) {
            file.setWritable(false);
        } else {
            file.setWritable(true);
        }
        
    }

    public void attrReadOnly(File file) throws IOException {
//        if (file.canRead()()) {
//            file.setWritable(false);
//        } else {
//            file.setWritable(true);
//        }
        
    }
}
